<template>
  <div class="container">
    <div class="formula-content line_feed" v-html="renderedContent"></div>
  </div>
</template>

<script>
import katex from 'katex'
import 'katex/dist/katex.min.css'

export default {
  props: {
    content: {
      type: String,
      required: true
    }
  },
  computed: {
    renderedContent() {
      let normalized = this.content.replace(/\\\[([\s\S]*?)\\\]/g, '$$$1$$');

      // 替换 \(...\) 为 $...$
      normalized = normalized.replace(/\\\(([\s\S]*?)\\\)/g, '$$1$');
      // 替换 $...$ 和 $$...$$ 为 KaTeX 渲染的 HTML
      return normalized.replace(/\$\$([^$]+)\$\$|\$([^$]+)\$/g, (match, p1, p2) => {
        const formula = p1 || p2
        try {
          return katex.renderToString(formula, {
            throwOnError: false
          })
        } catch (e) {
          console.error('KaTeX rendering error:', e)
          return match
        }
      })
    }
  }
}
</script>

<style>
.formula-content {
  line-height: 1.6;
  white-space: pre-line;
}
</style>
